package com.cn.zengzeng.spbzengzeng.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: ZhangZengZeng
 * @Date: 2023/3/22 11:33
 */
class ShareRes{
    private int num = 1; //A:1,B:2,C:3
    private ReentrantLock lock = new ReentrantLock();
    private Condition conditionA  = lock.newCondition();
    private Condition conditionB  = lock.newCondition();
    private Condition conditionC  = lock.newCondition();
    void print1(){
        lock.lock();
        try {
            while (num != 1){
                conditionA.await();
            }
            for (int i = 1; i <= 1; i++) {
                System.out.println(Thread.currentThread().getName()+"  "+i);
            }
            num = 2;
            conditionB.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    void print2(){
        lock.lock();
        try {
            while (num != 2){
                conditionB.await();
            }
            for (int i = 1; i <= 2; i++) {
                System.out.println(Thread.currentThread().getName()+"  "+i);
            }
            num = 3;
            conditionC.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    void print3(){
        lock.lock();
        try {
            while (num != 3){
                conditionC.await();
            }
            for (int i = 1; i <= 3; i++) {
                System.out.println(Thread.currentThread().getName()+"  "+i);
            }
            num = 1;
            conditionA.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}

public class LockTraditionDemo {

    public static void main(String[] args) {
        final ShareRes res = new ShareRes();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    res.print1();
                }
            }
        },"线程A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    res.print2();
                }
            }
        },"线程B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    res.print3();
                }
            }
        },"线程C").start();

        int a = -5 ;
    }


}
